package com.example.gorannet;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class TicketDetailsActivity extends Activity {
    EditText t;

    BootstrapButton reg, editButton, btnSygic,  submit, sql_btn,toggle;

    EditText                              subj, ticket, tel, status, pior, cret_on, mobile,
    neihbor, addr2, site, pair, username, password;
    private String alertHeaderText = "Evaluation";
    private String alertText = " Dear customer.. \n Would you like to give us your feedback?! \n Your feedback is helping us in improving \n our services.";
   
    TextView                              posted, from, conver;
    EditText                              alley, street;
    String                                pid;
    String[]                              ticketDetail    = new String[21];
    static String ticket_no = "", employee_id = "";
    static long ticket_date = 0;
    JSONParser                            jsonParser      = new JSONParser();
    private BootstrapButton                         btnSettings, btnProfile, btnPrivacy,
    btnConversation, btnEditProperty;
    static int act = 0;
    private View                          panelSettings, panelProfile, panelPrivacy,
    panelEditProperty, panelConversation;
    public static final String            ARG_ITEM_ID     = "item_id";

    private AlertDialogManager            alert           = new AlertDialogManager();


    AsyncTask<Void, Void, Void>           mRegisterTask;

    private static final String           edit_url        = "http://db.gorannet.net/DB/Technical/tickets/check_ticket.php";
    private String          tempStr[] = new String[4];

    private Spinner        statusCombo;

    BootstrapEditText       replay;
    String ticketNo;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.accordion);
        Intent in = getIntent();

        ticketNo = in.getStringExtra("TICKET");

        subj = (EditText)findViewById(R.id.txtName);
        subj.setEnabled(false);
        ticket = (EditText)findViewById(R.id.txtSurname);
        ticket.setEnabled(false);
        tel = (EditText)findViewById(R.id.editText1);
        tel.setEnabled(false);
        status = (EditText)findViewById(R.id.editText2);
        status.setEnabled(false);
        pior = (EditText)findViewById(R.id.editText3);
        pior.setEnabled(false);
        cret_on = (EditText)findViewById(R.id.EditText01);
        cret_on.setEnabled(false);
        mobile = (EditText)findViewById(R.id.editText4);
        mobile.setFocusable(false);
        mobile.setClickable(true);
        neihbor = (EditText)findViewById(R.id.editText5);
        neihbor.setEnabled(false);
        alley = (EditText)findViewById(R.id.editText6);
        alley.setEnabled(false);
        street = (EditText)findViewById(R.id.editText7);
        street.setEnabled(false);
        addr2 = (EditText)findViewById(R.id.editText8);
        addr2.setEnabled(false);
        site = (EditText)findViewById(R.id.editText9);
        site.setEnabled(false);
        pair = (EditText)findViewById(R.id.editText10);
        pair.setEnabled(false);
        username = (EditText)findViewById(R.id.editText11);
        username.setEnabled(false);
        password = (EditText)findViewById(R.id.editText12);
        password.setEnabled(false);
        LinearLayout convsLinear = (LinearLayout)findViewById(R.id.convsLinear);

        String array_spinner[] =
            {
                "Open", "Closed", "On hold"
            };
        statusCombo = (Spinner)findViewById(R.id.statusCombo);
        statusCombo.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
                R.layout.single_list_item_view, R.id.product_label, array_spinner));
        panelProfile = findViewById(R.id.panelProfile);
        panelProfile.setVisibility(View.VISIBLE);
        panelSettings = findViewById(R.id.panelSettings);
        panelSettings.setVisibility(View.GONE);
        panelPrivacy = findViewById(R.id.panelPrivacy);
        panelPrivacy.setVisibility(View.GONE);
        panelConversation = findViewById(R.id.panelConversation);
        panelConversation.setVisibility(View.GONE);
        panelEditProperty = findViewById(R.id.panelEditProperty);
        panelEditProperty.setVisibility(View.GONE);
        btnProfile = (BootstrapButton)findViewById(R.id.btnProfile);
        btnSettings = (BootstrapButton)findViewById(R.id.btnSettings);
        btnPrivacy = (BootstrapButton)findViewById(R.id.btnPrivacy);
        btnConversation = (BootstrapButton)findViewById(R.id.btnConversation);
        btnEditProperty = (BootstrapButton)findViewById(R.id.btnEditProperty);
        btnProfile.setOnTouchListener(new View.OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                // TODO Auto-generated method stub
                panelSettings.setVisibility(View.GONE);
                panelProfile.setVisibility(View.VISIBLE);
                panelPrivacy.setVisibility(View.GONE);
                panelConversation.setVisibility(View.GONE);
                panelEditProperty.setVisibility(View.GONE);
                return false;
            }
        });
        btnPrivacy.setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                // TODO Auto-generated method stub
                panelSettings.setVisibility(View.GONE);
                panelProfile.setVisibility(View.GONE);
                panelPrivacy.setVisibility(View.VISIBLE);
                panelConversation.setVisibility(View.GONE);
                panelEditProperty.setVisibility(View.GONE);
                return false;
            }
        });
        btnSettings.setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                // TODO Auto-generated method stub
                panelSettings.setVisibility(View.VISIBLE);
                panelProfile.setVisibility(View.GONE);
                panelPrivacy.setVisibility(View.GONE);
                panelConversation.setVisibility(View.GONE);
                panelEditProperty.setVisibility(View.GONE);
                return false;
            }
        });
        btnConversation.setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                // TODO Auto-generated method stub
                panelSettings.setVisibility(View.GONE);
                panelProfile.setVisibility(View.GONE);
                panelPrivacy.setVisibility(View.GONE);
                panelConversation.setVisibility(View.VISIBLE);
                panelEditProperty.setVisibility(View.GONE);
                return false;
            }
        });
        btnEditProperty.setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                // TODO Auto-generated method stub
                panelSettings.setVisibility(View.GONE);
                panelProfile.setVisibility(View.GONE);
                panelPrivacy.setVisibility(View.GONE);
                panelConversation.setVisibility(View.GONE);
                panelEditProperty.setVisibility(View.VISIBLE);
                return false;
            }
        });

        DBHandler db = new DBHandler(getApplicationContext());
        ticketDetail = db.getTicketDetails(ticketNo);
        ticket.setText(ticketDetail[0]);
        subj.setText(ticketDetail[1]);
        tel.setText(ticketDetail[2]);
        status.setText(ticketDetail[3]);
        pior.setText(ticketDetail[4]);
        cret_on.setText(ticketDetail[5]);
        mobile.setText(ticketDetail[6]);
        neihbor.setText(ticketDetail[7]);
        alley.setText(ticketDetail[8]);
        street.setText(ticketDetail[9]);
        addr2.setText(ticketDetail[10]);
        site.setText(ticketDetail[12]);
        pair.setText(ticketDetail[13]);
        username.setText(ticketDetail[14]);
        password.setText(ticketDetail[15]);

        ticket_no = ticketNo;
        employee_id = ticketDetail[17];
        
        replay = (BootstrapEditText)findViewById(R.id.srchEdtxt);
        editButton = (BootstrapButton)findViewById(R.id.btnEdit);
        mobile.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(TicketDetailsActivity.this);
		        builder.setTitle("Call Confirmation")
		        .setMessage("Do you want to call " + mobile.getText()+" ?").setIcon(android.R.drawable.ic_dialog_info)
		                .setPositiveButton("YES", new DialogInterface.OnClickListener()
		                {
		                    @Override
		                    public void onClick(DialogInterface dialog, int which)
		                    {
		                    	Intent callIntent = new Intent(Intent.ACTION_CALL);
		        				callIntent.setData(Uri.parse("tel:"+mobile.getText()));
		        				startActivity(callIntent);
		                    }
		                }).setNegativeButton("NO", new DialogInterface.OnClickListener()
		                {
		                    @Override
		                    public void onClick(DialogInterface dialog, int which)
		                    {
		                    	Toast.makeText(getApplicationContext(), "Call Canceled",Toast.LENGTH_LONG).show();
		                    }
		                })

		                .show();				
			}
		});
        editButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {

                if((replay.getText().toString()).equals("")){
                	alert.showAlertDialog(TicketDetailsActivity.this, "Warning",
                            "Please fill the post replay field", false);
                }else{
                    DBHandler db = new DBHandler(getApplicationContext());
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("ticket", ticketDetail[0]);
                    params.put("status", statusCombo.getSelectedItem().toString());
                    params.put("replay", replay.getText().toString());
                    String [] conversationReverse = ticketDetail[18].split(" ");
                    String fromTo = conversationReverse[2]+" "+conversationReverse[1]+" "+conversationReverse[0];
                    long now = System.currentTimeMillis();
                    db.insertComments(ticketDetail[0], replay.getText().toString(), fromTo, "1", now);
                    try
                    {
                        String serverUrl = edit_url;
                        post(serverUrl, params);

                        db.updateTicketDetails(ticket.getText().toString(), statusCombo
                            .getSelectedItem().toString(), "High");
                        replay.setText("");
                        if(statusCombo.getSelectedItem().toString().equalsIgnoreCase("Closed"))
                        {
                            ticket_date = System.currentTimeMillis();
                            act = 1;
                            AlertDialog.Builder builder = new AlertDialog.Builder(TicketDetailsActivity.this);
                            builder.setTitle(alertHeaderText)
                            .setMessage(
                                    alertText)
                                    .setIcon(android.R.drawable.ic_dialog_info)
                                    .setPositiveButton("YES", new DialogInterface.OnClickListener()
                                    {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which)
                                        {
                                        	Intent i = new Intent(getApplicationContext(), evaluation.class);
                                            startActivity(i);
                                        }
                                    }).setNegativeButton("NO", new DialogInterface.OnClickListener()
                                    {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which)
                                        {
                                            Intent i = new Intent(getApplicationContext(), CaptureSignature.class);
                                            i.putExtra("doeval", "no");
                                            i.putExtra("comm", "0");
                                            i.putExtra("understand", "0");
                                            i.putExtra("prof", "0");
                                            i.putExtra("timeV", "0");
                                            startActivity(i);
                                        }
                                    })

                                    .show();
                        }
                    }
                    catch (Exception e)
                    {
                        Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG).show();
                    }
                }
               // if()
            }

        });


        String[] convArray = db.getConversations(ticketDetail[0]);
        TextView textViewLeft;
        TextView textViewRight;
        for (int i = 0; i < convArray.length; i++)
        {
            tempStr = convArray[i].split("@:@");

            if (tempStr[0].equals("0"))
            {
                textViewLeft = new TextView(getApplicationContext());
                textViewLeft.setText(tempStr[2] + " says: " + "\r\n\r\n" + tempStr[1]);
                textViewLeft.setTextColor(getResources().getColor(R.color.black));
                textViewLeft.setBackgroundResource(R.drawable.speech_bubble_orange);
                textViewLeft.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT));
                convsLinear.addView(textViewLeft);
            }
            if (tempStr[0].equals("1"))
            {
                textViewRight = new TextView(getApplicationContext());
                textViewRight.setText(tempStr[2] + " says: " + "\r\n\r\n" + tempStr[1]);
                textViewRight.setTextColor(getResources().getColor(R.color.black));
                textViewRight.setBackgroundResource(R.drawable.speech_bubble_green);
                textViewRight.setGravity(Gravity.RIGHT);
                /*textViewRight.setLayoutParams(new
                        LayoutParams(LayoutParams.WRAP_CONTENT,
                                LayoutParams.WRAP_CONTENT));*/
                convsLinear.addView(textViewRight);
            }
        }

        // sygic button
        btnSygic = (BootstrapButton)findViewById(R.id.syg);
        // new GetProductDetails().execute();
        btnSygic.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {
                // starting background task to update product
                String addr1 = alley.getText().toString();
                String addr2 = street.getText().toString();

                if (!(addr1.equals("") || addr2.equals("")))
                {
                    String str = "com.sygic.aura://address|Iraq|Sulaimani||" + addr1 + "?" + addr2 + "||drive";
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(str)));

                }else
                    alert.showAlertDialog(getApplicationContext(), "Warning",
                            "No detile found!", false);

            }
        });

        /*view.setOnKeyListener(new OnKeyListener()
    {

        @Override
        public boolean onKey(View view, int intKeyCode, KeyEvent keyEvent)
        {
            Toast.makeText(view.getContext(), "Pressed", Toast.LENGTH_LONG).show();
            if (intKeyCode == KeyEvent.KEYCODE_BACK)
            {
                Toast.makeText(getApplicationContext(), "Back Pressed1", Toast.LENGTH_LONG).show();
                return true;
            }
            return true;
        }
    });*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.layout.menu, menu);
        return true;
    }

    private static void post(String endpoint, Map<String, String> params) throws IOException
    {
        URL url;
        try
        {
            url = new URL(endpoint);
        }
        catch (MalformedURLException e)
        {
            throw new IllegalArgumentException("invalid url: " + endpoint);
        }
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
        // constructs the POST body using the parameters
        while (iterator.hasNext())
        {
            Entry<String, String> param = iterator.next();
            bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
            if (iterator.hasNext())
            {
                bodyBuilder.append('&');
            }
        }
        String body = bodyBuilder.toString();
        // Log.v(TAG, "Posting '" + body + "' to " + url);
        byte[] bytes = body.getBytes();
        HttpURLConnection conn = null;
        try
        {
            Log.e("URL", "> " + url);
            conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.close();
            // handle the response
            int status = conn.getResponseCode();
            if (status != 200)
            {
                throw new IOException("Post failed with error code " + status);
            }
        }
        finally
        {
            if (conn != null)
            {
                conn.disconnect();
            }

        }
    }

}